package net.hsxin.test.activiti.controller;

import java.util.List;

import javax.annotation.Resource;

import net.hsxin.test.activiti.service.ProcessService;
import net.hsxin.test.activiti.service.TasksService;

import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class ActivitiWebController
{
	@Resource
	private ProcessService processService;
	
	@Resource
	private TasksService tasksService;

	public ProcessService getProcessService()
	{
		return processService;
	}

	public TasksService getTasksService() {
		return tasksService;
	}

	public void setTasksService(TasksService tasksService) {
		this.tasksService = tasksService;
	}

	public void setProcessService(ProcessService processService)
	{
		this.processService = processService;
	}

	@RequestMapping(value = "/index")
	@ResponseBody
	public String index()
	{
		List<ProcessDefinition> list = this.processService.getDeployProcesses();
		StringBuffer sBuffer = new StringBuffer();
		for(ProcessDefinition define : list)
		{
			sBuffer.append(define.getKey()).append(";");
		}
		
		return sBuffer.toString();
	}
	
	@RequestMapping(value = "/createdProcessesList")
	@ResponseBody
	public String createdProcessesList()
	{
		List<ProcessInstance> list = this.processService.getCreatedProcesses();
		StringBuffer sBuffer = new StringBuffer();
		for(ProcessInstance instance : list)
		{
			sBuffer.append(instance.getId()).append(";");
		}
		
		return sBuffer.toString();
	}
	
	@RequestMapping(value = "/createProcess")
	@ResponseBody
	public String createProcess(@RequestParam(value = "key") String processKey)
	{
		ProcessInstance instance = this.processService.createProcess(processKey);
		return instance.getId();
	}
	
	@RequestMapping(value = "/listTasks")
	@ResponseBody
	public String listTasks(@RequestParam(value = "key") String processKey)
	{
		List<Task> tasks = this.tasksService.listTasks(processKey);
		StringBuffer sBuffer = new StringBuffer();
		for(Task task : tasks)
		{
			sBuffer.append(task.getId()).append(";");
		}
		return sBuffer.toString();
	}
	
	@RequestMapping(value = "/completeTask")
	@ResponseBody
	public String completeTask(@RequestParam(value = "taskId") String taskId)
	{
		this.tasksService.completeTask(taskId);
		
		return "OK";
	}
}
